package com.tywj.panda.launch

import android.os.Bundle
import com.blankj.utilcode.util.BarUtils
import com.tywj.panda.customer.common.api.CommonApi
import com.tywj.panda.customer.common.cache.CommonCache
import com.tywj.panda.customer.common.entity.UpdateTokenEntity
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.route.CommonRoute
import com.tywj.panda.customer.common.tool.AuthorityTool
import com.tywj.panda.customer.common.tool.CacheTool
import com.tywj.panda.customer.common.view.base.PDBaseWithoutAdaptActivity
import com.tywj.panda.launch.route.LaunchRoute
import com.tywj.lib.core.common.extension.applyScheduler
import com.tywj.lib.core.common.manager.ActivityManager
import com.tywj.lib.core.common.util.AppUtil
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.lifecycle.extension.attachToLifecycle
import io.reactivex.Observable
import org.jetbrains.anko.doAsync
import java.util.concurrent.TimeUnit

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/12
 *     desc   : 启动页
 *     version: 1.0
 * </pre>
 */
class SplashActivity : PDBaseWithoutAdaptActivity() {

    companion object {
        // 启动页最少停留时间
        private const val STAY_TIME_MIN = 1000L
    }

    // 是否关闭当前Activity
    private var finishCurActivity = false

    // Activity创建时间
    private var createTime = 0L

    override fun getLayoutID(): Int = 0

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        createTime = System.currentTimeMillis()

        // 兼容性代码，当华为推送数量超过一定数量时，会将推送打组，点击打组时，不管App是否已经启动，都会启动启动页
        if (ActivityManager.getMainActivity() != null) {
            ActivityManager.closeListActivity()
            AppUtil.moveAppToFront()
            finishCurActivity = true
        } else if (ActivityManager.getActivityList().size > 1) {
            finish()
            AppUtil.moveAppToFront()
            finishCurActivity = true
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        BarUtil.invasionStatusBar(this)
        BarUtils.setNavBarVisibility(this, false)
    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()

        if (!finishCurActivity) {
            checkAppUpdate()
        }
    }

    //需要判断司机端还是用户端登录
    private fun toMainActivity() {
        val userType = CommonCache.userType

        if (userType == 1) {
            CommonRoute.toMainCustomer().navigation(this) { finish() }
        } else {
            CommonRoute.toMainDriver().navigation(this) { finish() }
        }
    }

    private fun checkAppUpdate() {
        LogUtil.d("检查升级")
        //一般在用户检查是否有升级后再启动
        delayTimeToActivity()
    }

    private fun delayTimeToActivity() {
        val interval = createTime + STAY_TIME_MIN - System.currentTimeMillis()
        if (interval > 0) {
            Observable.just("")
                .delay(interval, TimeUnit.MILLISECONDS)
                .applyScheduler()
                .subscribe { verifyToActivity() }
                .attachToLifecycle(this@SplashActivity)
        } else {
            verifyToActivity()
        }
    }

    private fun verifyToActivity() {

        verifyToGuideActivity()

//        if (AuthorityTool.token.isEmpty()) {
//            // token为空，用户没有登录，判断是否进入引导界面
//            verifyToGuideActivity()
//        } else {  //token不为空，说明用户处于登录状态，更新token
//            updateToken()
//        }
    }

    private fun updateToken() {
        val userInfo = CommonCache.userInfo
        if (userInfo == null) {
            verifyToGuideActivity()
            return
        }
        //初始化用户相关缓存
        CacheTool.initUserGlobalCache(userInfo.uid)

        CommonApi.updateToken()
            .attachToLifecycle(this)
            .execute(object :
                PDObjectCallback<UpdateTokenEntity>(UpdateTokenEntity::class.java, true) {
                override fun success(data: UpdateTokenEntity) {
                    // 更新token
                    AuthorityTool.updateToken(data.token)
                    verifyToGuideActivity()
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)

                    // 网络异常还是按原逻辑处理，保证用户在离线前处于登录状态离线，也能进入首页
                    if (code < 0) {
                        verifyToGuideActivity()
                    } else {
                        // 清空数据
                        doAsync { CacheTool.localCache.clear() }
                        AuthorityTool.clear()
                        verifyToGuideActivity()
                    }
                }
            })
    }

    private fun verifyToGuideActivity() {
        verifyToAdActivity()
    }

    //去掉广告
    private fun verifyToAdActivity() {
        if (AuthorityTool.token.isNotEmpty()) { //token存在，用户处于登录状态，进入主界面
            LogUtil.d("去主界面")
            toMainActivity()
        } else {
            //token不存在，用户没有登录
            LogUtil.d("去登录")
            toLoginActivity()
        }
    }

    private fun toLoginActivity() {
        LaunchRoute.toLoginByPhone().navigation(this) { finish() }
    }
}